package com.crfchina.consumer.eurekaconsumer.Controller;

import com.crfchina.consumer.eurekaconsumer.pojo.User;
import com.crfchina.consumer.eurekaconsumer.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class ConsumerController {

//     @Autowired
//   LoadBalancerClient loadBalancerClient;
   @Autowired
    RestTemplate restTemplate;

//@RequestMapping(value = "/consumer",method = RequestMethod.GET)

    //使用原始的方式
//   public String dc() {
//       ServiceInstance serviceInstance = loadBalancerClient.choose("compute-service");
//       String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/add?a=3&b=4";
//       System.out.println(url);
//       return restTemplate.getForObject(url, String.class);
//   }
   //使用ribbon方式实现客户端负载均衡(get请求)
    @RequestMapping(value = "/consumer1",method = RequestMethod.GET)
    public String dc1() {
        return restTemplate.getForEntity("http://COMPUTE-SERVICE/add?a=10&b=20", String.class).getBody();
    }
    //使用ribbon方式实现客户端负载均衡(post请求")
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String user(){
        User user = new User();
        user.setId(3l);
        user.setName("wufei");
        user.setAge("18");
       return restTemplate.postForEntity("http://COMPUTE-SERVICE/user", user, String.class).getBody();
    }

    //测试断路器的使用
    @Autowired
    private ConsumerService consumerService;
    @RequestMapping(value = "/consumer2",method = RequestMethod.GET)
    public String dc2() {
        return  consumerService.addService();
    }
}